got hooks?

2024-02-06

Hooks, some I've seen and used while others not so much.

useRef

A particular use case for this is when one needs to interact directly with the actual DOM (not react's). Previously, this hook was used for a modal where I needed to target the same element each time. In comparison, something within React, where React updates according to state (which is great), one can see where having outside of that would make sense.

memo

"tells React "as long as the parameters being passed into this component don't change, do not re-render it ever." sn: this is not something to get wild with, use when necesssary as things can end up not re-rendering when expected and it's because you memoized it. On that note, you don't want something re-rendering unneccessarily, for example, performance reasons/etc.

useReducer

If you've come across Redux, reducer sounds familiar. Basically, this is the idea but from inside a hook. One reducer that handles all upodates based on action. Good use case, complex state changes or all updates similar enough to contain them within one fn.

useMemo

useMemo and useCallback are for optimizing performance, to be used only after performance problem discovery (doing otherwise adds unnecessary complexity).

So what does it do? memoizes expensive function calls to only be re-evaluated as needed/specified (much like the [] w/ useEffect where you are telling it to run when w.e you put in there changes).

useCallback

Similar to useMemo, implemented with same mechanisms. Again, to have absolutely necessary re-renders. Normally, when react detects a change higher-up in the app it re-renders what's below as well. Typically, not an issue, unless you happen to have a component where this should only happen for reasons (ie: performance).

memo provides a check to see if anything has changed, making sure it is the same function given each time.

useLayoutEffect

Similar to useEffect, except it is synchronous (immediate). Seems like it could be good to use when needing to measure something within the DOM, ex: animations. Like, I assume having a bouncing ball, it would need to know where the ball was prior and then presently so that render would need to happen instant/synchronously. In comparison to a useEffect where it comes into play after an initial render or after some dependency change, there's this brief pause, like next frame and then run.

useID

React 18, new hook. Unique identifiers to associate objects. An example, label/input associations by htmlFor attr.

Before, maintaining a unique counter across renders was possible, but with concurrent and batching in v18 of React, not possible. useID is consistent, safe across server-side and client-side.

For multiple IDs, no need to call hook multiple times. Instead, use id and append to it, ex: {id}-username, {id}-user, etc.

additional hooks?

Plenty more out there... those above, seem like, you'd have more chance encountering out in the wild.


← go back